package com.xkxbx.kkk.dyw;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetWorkStateReceiver extends BroadcastReceiver {

    public TWebView webView;

    private boolean isConnected = true;

    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("网络状态发生变化");
        //检测API是不是小于23，因为到了API23之后getNetworkInfo(int networkType)方法被弃用
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {

            //获得ConnectivityManager对象
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            NetworkInfo wifiNetworkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            //获取移动数据连接的信息
            NetworkInfo dataNetworkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (!wifiNetworkInfo.isConnected() && !dataNetworkInfo.isConnected()) {
                System.out.println("WIFI已断开,移动数据已断开");
                isConnected = false;
            } else {
                if (isConnected == false){
                    isConnected = true;
                    if (webView.isLoad == false){
                        System.out.println("重新加载页面");
                        webView.reload();
                    }
                }
            }
        }else {
            //API大于23时使用下面的方式进行网络监听
            System.out.println("API level 大于23");
            // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            // 获取NetworkInfo对象
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            if (networkInfo != null){
                if (isConnected == false){
                    isConnected = true;
                    if (webView.isLoad == false){
                        System.out.println("重新加载页面");
                        webView.reload();
                    }
                }
            }else {
                isConnected = false;
            }
        }
    }
}
